package class3;

import com.google.common.collect.Lists;
import common.ListNode;
import common.ListNodeUtils;

/**
 * https://leetcode.cn/problems/sum-lists-lcci/description/
 * 链表求和
 */
public class Code31_addTwoNumbers {
    public static void main(String[] args) {
        ListNode head1 = ListNodeUtils.getLinked(5);
        ListNode head2 = ListNodeUtils.getLinked(5);
        ListNode listNode = addTwoNumbers(head1, head2);
        ListNodeUtils.print(listNode);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = getLen(l1);
        int len2 = getLen(l2);

        ListNode l = len1 >= len2 ? l1 : l2;
        ListNode s = l == l1 ? l2 : l1;

        ListNode curL = l, curS = s,last=null;

        int c = 0, t = 0;
        for (; curS != null; curL = curL.next, curS = curS.next) {
            t = curL.val + curS.val + c;
            curL.val = t % 10;
            c = t / 10;
            last = curL;
        }

        for (; curL != null; curL = curL.next) {
            t = curL.val + c;
            curL.val = t % 10;
            c = t / 10;
            last = curL;
        }
        if (c == 1) {
            last.next = new ListNode(1);
        }


        return l;
    }

    public static int getLen(ListNode head) {
        int size = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            size++;
        }
        return size;
    }
}
